﻿using UnityEngine;
using XNode;

namespace ActionGraph.Core
{
    [NodeHideInCreateMenu]
    public class ActionNode : Node
    {
        protected          ActionGraph     parent =>graph as ActionGraph;
        protected          ActionGraphHost host   => parent.graphHost;
        protected          GameEntity      entity => parent.graphHost.entity;
        protected internal bool            HasExcuted = false; //标记是否被执行
        private bool Enter ()
        {
            OnEnter ();

            return OnExcute ();
        }

        private void Exit ()
        {
            OnExit ();
        }

        public bool Excute ()
        {
            HasExcuted = false;
            var ret = OnExcute ();
            if (ret==false)
            {
                parent.graphHost.RegisterExcute (this);
            }
            HasExcuted = true;
            return ret;
        }

        protected virtual void OnEnter ()
        {
            
        }

        protected virtual void OnExit ()
        {
            
        }

        protected virtual bool OnExcute ()
        {
            return true;
        }

        protected bool ExitNode (string portName)
        {
            var exitPort = GetOutputPort (portName);

            if (exitPort==null)
            {
                Debug.LogError ("Exit Port is Null");
                return true;
            }

            if (exitPort.IsConnected==false)
            {
                return true;
            }

            //出口连接的节点
            var node = exitPort.Connection.node as ActionNode;
            return node.Enter ();
        }
    }
}